<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="存储名称" prop="storageName">
        <el-input
          v-model="queryParams.storageName"
          placeholder="请输入存储名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-input
          v-model="queryParams.source"
          placeholder="请输入来源"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['knowledge:storage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['knowledge:storage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['knowledge:storage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['knowledge:storage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="存储名称" align="center" prop="storageName" />
      <el-table-column label="来源" align="center" prop="source" >
        <template #default="scope">
          <el-tag v-if="scope.row.source === 'CUSTOMIZE'" type="success">自定义</el-tag>
          <el-tag v-else type="info">系统默认</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="配置限额" align="center" prop="quotaSize" />
      <el-table-column label="存储类型" align="left" prop="storageType" >
        <template #default="scope">
          <el-tag type="success">{{storageTypeObj[scope.row.storageType]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 'enabled'">启用</el-tag>
          <el-tag type="warning" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createUser" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope" v-show="scope.row.source === 'CUSTOMIZE'">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['knowledge:storage:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['knowledge:storage:remove']">删除</el-button>
          <el-button link type="primary" icon="Remove" @click="handleUpdate(scope.row)" v-hasPermi="['knowledge:storage:edit']"  v-if="scope.row.status === 'enabled'">停用</el-button>
          <el-button link type="primary" icon="Open" @click="handleUpdate(scope.row)" v-hasPermi="['knowledge:storage:edit']"  v-if="scope.row.status === 'disabled'">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改存储对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="storageRef" :model="form" label-width="100px" :inline="true" class="operate-form">
        <el-form-item label="存储类型" prop="storageType" :rules="[{ required: true, message:'存储类型不能为空', trigger: 'blur' }]">
          <el-select v-model="form.storageType" placeholder="请选择存储类型">
            <el-option v-for="item in storageTypeList" :key="item.type" :label="item.name" :value="item.type"/>
          </el-select>
        </el-form-item>
        <el-form-item label="存储名称" prop="storageName" :rules="[{ required: true, message:'存储名称不能为空', trigger: 'blur' },{ min: 3, max: 10, message: '最少3个字符最多10个字符', trigger: 'blur' }]">
          <el-input v-model="form.storageName" placeholder="请输入存储名称" />
        </el-form-item>
        <div v-if="form.storageType === 'local_filesystem'">
          <el-form-item label="上传地址" prop="storageConfig.uploadUrl" :rules="{ required: true, message:'上传地址不能为空', trigger: 'blur' }">
            <el-input v-model="form.storageConfig.uploadUrl" placeholder="请输入上传地址" />
          </el-form-item>
          <el-form-item label="下载地址" prop="storageConfig.downloadUrl" :rules="{ required: true, message:'下载地址不能为空', trigger: 'blur' }">
            <el-input v-model="form.storageConfig.downloadUrl" placeholder="请输入下载地址" />
          </el-form-item>
          <el-form-item label="预览地址" prop="storageConfig.previewUrl" :rules="{ required: true, message:'预览地址不能为空', trigger: 'blur' }">
            <el-input v-model="form.storageConfig.previewUrl" placeholder="请输入预览地址" />
          </el-form-item>
          <el-form-item label="存储编号" prop="storageConfig.storageCode" :rules="{ required: true, message:'存储编号不能为空', trigger: 'blur' }">
            <el-input v-model="form.storageConfig.storageCode" placeholder="存储编号" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Storage">
import { pageListStorage, listStorage, getStorage, delStorage, addStorage, updateStorage, typeList } from "@/api/knowledge/storage";

const { proxy } = getCurrentInstance();

const storageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const storageTypeList = ref([]);
const storageTypeObj = reactive({})
const data = reactive({
  form: {storageConfig:{
      folderStrategy: "date",
    }},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: null,
    storageName: null,
    source: null,
    quotaSize: null,
    storageType: null,
    status: null,
    createdBy: null,
    createUser: null,
    updatedBy: null,
    updateUser: null
  },
  rules: {
    storageType: [
      { required: true, message: "存储类型不能为空", trigger: "blur" }
    ],
    storageName: [
      { required: true, message: "存储名称不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

watch( () => storageTypeList.value, () => {
  storageTypeList.value.forEach(item => {
    storageTypeObj[item.type] = item.name
  }, { immediate: true, deep: true })
})

/** 查询存储列表 */
function getList() {
  loading.value = true;
  pageListStorage(queryParams.value).then(response => {
    storageList.value = response.data.list;
    total.value = response.data.list.length;
    loading.value = false;
  });
}

function getTypeList(){
  typeList().then(response => {
    storageTypeList.value = response.data
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tenantId: null,
    storageName: null,
    source: null,
    quotaSize: null,
    storageType: null,
    storageConfig: {
      folderStrategy: 'date',
      randomDeep:3,
      randomSize: 256,
      rootPath: "",
      dateStr: ["yyyy","MM","dd"]
    },
    status: null,
    createTime: null,
    createdBy: null,
    createUser: null,
    updateTime: null,
    updatedBy: null,
    updateUser: null
  };
  proxy.resetForm("storageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存储";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStorage(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改存储";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storageRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStorage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStorage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除存储编号为"' + _ids + '"的数据项？').then(function() {
    return delStorage(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('knowledge/storage/export', {
    ...queryParams.value
  }, `storage_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getTypeList();
})
</script>

<style lang="scss" scoped>
.operate-form .el-input {
  width: 200px;
}

.operate-form .el-select {
  width: 200px;
}

.operate-form .el-input-number {
  width: 200px;
}
.operate-form .el-radio-group {
  width: 200px;
}
</style>
